package com.yh.csx.bsf.web;

import com.yh.csx.bsf.core.base.Callable;
import com.yh.csx.bsf.core.util.ExceptionUtils;
import com.yh.csx.bsf.core.util.JsonUtils;
import com.yh.csx.bsf.core.util.TimeWatchUtils;
import com.yh.csx.bsf.web.template.HtmlHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 扩展SpringController的实现，采用lambada表达式的方式进行类似aop的拦截
 */
@Slf4j
public class BaseController {
    @Autowired(required = false)
    protected HttpServletRequest request;

    @Autowired(required = false)
    protected HttpServletResponse response;

    protected HtmlHelper html = new HtmlHelper();
    protected String errorUrl="/systemerror/index/";

    /**
     * 页面统一默认拦截器 页面模式
     * @param visit
     *        java8语法：传进来的是方法块，实现类
     * @return
     */
    protected ModelAndView pageVisit(Callable.Action1<ModelAndView> visit) {
        return TimeWatchUtils.print(true,request.getRequestURI(), () -> {
            ModelAndView modelAndView = null;
            try {
                //页面模板扩展方法
                request.setAttribute("Html", html);
                //request.setAttribute("user", User.getCurrent());
                //默认视图地址为/contoller name/method name,即结构对应一致
                modelAndView = new ModelAndView();
                visit.invoke(modelAndView);

                return modelAndView;
            } catch (Exception exp) {
                //默认错误拦截处理
                response.setStatus(500);
                modelAndView = new ModelAndView("forward:"+errorUrl);
                request.setAttribute("error", ExceptionUtils.getDetailMessage(exp));
                log.error("页面打开出错:" + request.getRequestURI(), exp);
            }
            return modelAndView;
        });
    }

    /**
     * Json 统一序列化
     *
     * @param visit
     * @return
     */
    protected ModelAndView jsonVisit(Callable.Func1<Object,ModelAndView> visit) {
        return TimeWatchUtils.print(true,request.getRequestURI(), () -> {
            ModelAndView modelAndView = new ModelAndView("");
            response.addHeader("Access-Control-Allow-Origin", "*");//跨域支持
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            try {
                Object jsondata = visit.invoke(modelAndView);
                jsondata = new HttpResponse(1,"",jsondata);
                String json = JsonUtils.serialize(jsondata);
                response.getWriter().write(json);
            } catch (Exception exp) {
                //默认错误拦截处理
                //response.setStatus(500);
                HttpResponse jsondata = new HttpResponse(-1, ExceptionUtils.getDetailMessage(exp),null);
                String json = JsonUtils.serialize(jsondata);
                try {
                    response.getWriter().write(json);
                } catch (Exception e) {
                }
                log.error("访问地址出错:" + request.getRequestURI(), exp);
            }
            modelAndView.setView(new View() {
                @Override
                public String getContentType() {
                    return null;
                }

                @Override
                public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
                }
            });
            return modelAndView;
        });
    }


}
